package com.zeus.core.factory;

import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.config.data.ZeusConfig;
import com.zeus.core.config.data.ZeusConfigDefault;
import com.zeus.core.open.spi.ZeusMonitor;
import com.zeus.core.report.ZeusReportClient;
import com.zeus.core.report.ZeusReportErrorClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 监控服务工厂
 *
 * @author f1ybear_wang 2021/5/13  1:36
 */
public class ZeusFactory {
    private static final Logger log = LoggerFactory.getLogger(ZeusFactory.class);

    /**
     * 线程池
     */
    private static final ThreadPoolExecutor executor =
        new ThreadPoolExecutor(5, 10, 5, TimeUnit.MINUTES, new ArrayBlockingQueue<>(5), (r, executor) -> {
            // 发送服务错误通知
            ZeusReportClient client = new ZeusReportErrorClient("宙斯服务已经超负荷运载了，线程池已经被沾满~");
            client.complete();
        });

    /**
     * 监控服务列表
     */
    private static List<ZeusMonitor> monitorList = new ArrayList<>();

    /**
     * 宙斯配置
     */
    private static ZeusConfig zeusConfig;

    /**
     * 初始化SPI服务
     * 
     * @author f1ybear_wang  2021/5/13 17:48
     */
    public static void initSpiService() {
        try {
            ServiceLoader<ZeusMonitor> zeusMonitorServiceLoader = ServiceLoader.load(ZeusMonitor.class);
            for (ZeusMonitor zeusMonitor : zeusMonitorServiceLoader) {
                monitorList.add(zeusMonitor);
            }
            if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.info("### 宙斯初始化SPI服务完成 >> monitorList = {}", monitorList.stream().filter(Objects::nonNull)
                    .map(ZeusMonitor::getClass).collect(Collectors.toList()));
            }
        } catch (Throwable e) {
            if (log.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.warn("### 宙斯初始化SPI服务出现异常:", e);
            }
        }
    }

    public static ThreadPoolExecutor getExecutor() {
        return executor;
    }

    /**
     * 获取监控服务列表
     *
     * @return List<ZeusMonitor> 监控服务列表
     * @author f1ybear_wang  2021/5/13 17:47
     */
    public static List<ZeusMonitor> getMonitorList() {
        return monitorList;
    }

    /**
     * 初始化宙斯配置
     * 
     * @return 宙斯配置
     * @author f1ybear_wang  2022/3/9 12:10 上午
     */
    public static ZeusConfig getZeusConfig() {
        if (zeusConfig == null) {
            zeusConfig = new ZeusConfigDefault();
        }
        return zeusConfig;
    }

}
